const createError = require('http-errors');
const multer = require('multer');
const logger = require('./logger');

/**
 * @param res
 * @param message
 * @param data
 * @param code
 * */
function success(res, message, data = {}, code = 200) {
  res.status(code).json({
    status: true,
    message,
    data,
  });
}

function failure(res, error) {
  let statusCode;
  let errors;
  switch (error.name) {
    case 'SequelizeValidationError':
      statusCode = 400;
      errors = error.errors.map((e) => e.message);
      break;
    case 'JsonWebTokenError':
      statusCode = 401;
      errors = 'Token异常或已过期';
      break;
    case 'TokenExpiredError':
      statusCode = 401;
      errors = 'Token异常或已过期';
      break;
    default:
      if (error instanceof multer.MulterError) {
        if (error.code === 'LIMIT_FILE_SIZE') {
          statusCode = 413;
          errors = '文件大小超出限制';
        } else {
          statusCode = error.status;
          errors = error.message;
        }
      } else {
        if (error instanceof createError.HttpError) {
          statusCode = error.status;
          errors = error.message;
        } else {
          statusCode = 500;
          errors = '服务器错误';
          logger.error('服务器错误:', error);
        }
      }
      break;
  }
  res.status(statusCode).json({
    status: false,
    message: `请求失败: ${error.name}`,
    errors: Array.isArray(errors) ? errors : [errors],
  });
}

module.exports = {
  success,
  failure,
};
